
from PIL import Image
import numpy as np
from matplotlib import pyplot as plt
import math

def asin2(y,x):
    r = math.sqrt(x**2+y**2)
    if x >=0 and y >= 0:
        return math.asin(y/r)
    elif x > 0 and y <= 0:
        return 2*math.pi + math.asin(y/r)
    elif x < 0 and y > 0:
        return math.pi - math.asin(y/r)
    else:
        return math.pi - math.asin(y/r)


im = Image.open("needle.png")
print("size:", im.size)
degrees = range(-90,-450,-6)

center = (im.size[0]/2, im.size[1]/2)
print("center:", center)
trace_point = (166,13)
print("trace_point:", trace_point)
print("delta x, delta y:", trace_point[0] - center[0], trace_point[1] - center[1])

r = math.sqrt((center[0]-trace_point[0])**2+(center[1]-trace_point[1])**2)
alpha = asin2(trace_point[1]- center[1], trace_point[0]-center[0])
print("alpha:", alpha, alpha*180/math.pi)
print("\n\n\n\n")

f = open("position.log", "w")
f.write("{\n")
for (i, degree) in enumerate(degrees):
    im_out = im.rotate(degree, expand = True, resample=Image.BICUBIC)
    out_center = (im_out.size[0]/2, im_out.size[1]/2)
    tmp = (r*math.cos(alpha+(degree*math.pi/180)), r*math.sin(alpha+(degree*math.pi/180)))
    new_trace  = (out_center[0]+r*math.cos(alpha+(degree*math.pi/180)), out_center[1]-r*math.sin(alpha+(degree*math.pi/180)))
    f.write("{.x = %d, .y = %d},\n"%new_trace)
    im_array = np.array(im_out)
    needle_center = np.array(new_trace).astype(np.uint16)
    im_out.save(str(i)+".png")
f.write("};\n")
